﻿using LIZTS.TODOS.Common.Models;
using LIZTS.TODOS.Extensions;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System.Collections.ObjectModel;

namespace LIZTS.TODOS.ViewModels
{
    public class MainViewModel : BindableBase
    {
        public DelegateCommand<MenuBar> NavigateCommand { get; private set; }
        public DelegateCommand GoBackCommand { get; private set; }
        public DelegateCommand GoForwardCommand { get; private set; }

        private readonly IRegionManager regionManager;
        private IRegionNavigationJournal journal;
        
        private ObservableCollection<MenuBar> _menuBars;
        public ObservableCollection<MenuBar> MenuBars 
        { 
            get { return _menuBars; } 
            set 
            { 
                _menuBars = value;
                RaisePropertyChanged();
            }
        }

        public MainViewModel(IRegionManager regionManager)
        {
            this.regionManager = regionManager;
            this._menuBars = new ObservableCollection<MenuBar>();
            InitMenuBar();
            NavigateCommand = new DelegateCommand<MenuBar>(Navigate);
            GoBackCommand = new DelegateCommand(() =>
            {
                if (journal != null && journal.CanGoBack)
                {
                    journal.GoBack();
                }
            });

            GoForwardCommand = new DelegateCommand(() =>
            {
                if (journal != null && journal.CanGoForward)
                {
                    journal.GoForward();
                }
            });
        }

        private void Navigate(MenuBar menubar)
        {
            if ( menubar == null || string.IsNullOrWhiteSpace(menubar.NameSpace) )
            {
                return;
            }

            regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(menubar.NameSpace, back =>
            {
                journal = back.Context.NavigationService.Journal; 
            });
        }

        private void InitMenuBar()
        {
            MenuBars.Add(new MenuBar() { Icon = "Home", Title = "Home", NameSpace="IndexView"});
            MenuBars.Add(new MenuBar() { Icon = "NotebookOutline", Title = "Todos", NameSpace = "TodoView" });
            MenuBars.Add(new MenuBar() { Icon = "NotebookEditOutline", Title = "Memo", NameSpace = "MemoView" });
            MenuBars.Add(new MenuBar() { Icon = "Cog", Title = "Setting", NameSpace = "SettingView" });
        }
    }
}
